package zh.dummy.netty.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import zh.dummy.netty.core.protocol.NettyMessage;
import zh.dummy.netty.server.util.NettyUtil;

public class FinalChannelHandler extends ChannelHandlerAdapter{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ThreadLocal<String> local = new ThreadLocal<String>();
	
	public void channelRead(ChannelHandlerContext ctx,Object msg){
		NettyMessage message = (NettyMessage)msg;
		if(message.getHeader() != null && message.getHeader().getAttchment() != null){
			local.set(String.valueOf(message.getHeader().getAttchment().get("id")));
		}
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
		ctx.close();
		if(local.get() != null){
			logger.debug("remove channel , key :　" + local.get());
			NettyUtil.removeChannel(local.get());
		}
	}
}
